# backend/models/node.py
from datetime import datetime
from sqlalchemy import Boolean, String, Integer, DateTime, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from backend.db.base import Base
import uuid
from typing import List  # 添加这行导入


class Node(Base):
    __tablename__ = "nodes"

    id: Mapped[uuid.UUID] = mapped_column(primary_key=True, default=uuid.uuid4)
    name: Mapped[str] = mapped_column(String(100), nullable=False)
    host: Mapped[str] = mapped_column(String(100), nullable=False)
    port: Mapped[int] = mapped_column(Integer, nullable=False)
    protocol: Mapped[str] = mapped_column(String(20), nullable=True, default="wireguard")
    location: Mapped[str] = mapped_column(String(50), nullable=True)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)
    load_percent: Mapped[int] = mapped_column(Integer, nullable=True, default=0)

    # WireGuard 相关字段
    wg_public_key: Mapped[str] = mapped_column(String(255), nullable=True)
    wg_private_key: Mapped[str] = mapped_column(String(255), nullable=True)
    wg_endpoint: Mapped[str] = mapped_column(String(100), nullable=True)
    wg_port: Mapped[int] = mapped_column(Integer, default=51820)
    subnet: Mapped[str] = mapped_column(String(20), default="10.0.0.0/24")
    dns_servers: Mapped[str] = mapped_column(String(255), default="8.8.8.8,1.1.1.1")

    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)

    user_subscriptions = relationship("UserSubscription", back_populates="node")

    def get_dns_servers_list(self) -> List[str]:
        """将DNS服务器字符串转换为列表"""
        if self.dns_servers:
            return [dns.strip() for dns in self.dns_servers.split(',')]
        return ["8.8.8.8", "1.1.1.1"]